from enum import Enum

from flask import has_request_context, request
from zhconv import convert as zhc

from web.common.resp import fail_resp


class GreeksApiError(Exception):
    def __init__(self, code, msg, http_code=None):
        self.code = code
        self.msg = msg
        self.http_code = http_code

    def to_resp(self):
        return fail_resp(self.code, message=self.msg, http_status_code=self.http_code)

    def __str__(self):
        return f'code: {self.code}, msg: {self.msg}'


class ErrorCode(Enum):
    # TODO: 国际化需要替换成使用统一的locale
    # error_code, (en_msg, ch_msg)

    # BASIC
    NO_EXIST = 10404, ('{0} not exist', '{0}不存在')
    PARAMS_ERROR = 10400, ('params invalid: {0}', '参数非法： {0}')
    NO_AUTH = 10004, ('should be login', '需要登陆')
    PERMISSION_DENIED = 10403, ('Permission denied', '权限不足')
    TOO_MANY_REQUESTS = 10429, ('Too many requests', '请求过多')

    # Auth Error Code
    PASSWORD_ERROR = 11000, ('password error', '登陆密码错误')
    MFA_VERIFY_FAILED = 11001, ('Two factor verify failed', '双因素认证失败')
    AUTH_SERVER_ERROR = 11010, ('auth service error: {0}', 'auth服务错误: {0}')

    # Account errors
    EXCHANGE_ACCOUNT_EXIST = 12001, ('exchange {0} account is existed, can not repeat add', '交易所{0}账户已经存在，无法重复添加')
    EXCHANGE_NO_SUPPORT = 12002, ('exchange {0} no support', '不支持交易所: {0}')
    ACCOUNT_GROUP_NAME_EXIST = 12003, ('account group name [{0}] is exist', '账户组名称 [{0}] 已经存在')

    # Trade
    MIN_TRADE_SIZE_ERROR = 13001, ('min trade size is {0}', '最小交易数量为{0}')
    NotAllowInCreaseDelta = 13002, ('not allow increase delta', '不允许放大delta敞口')
    # INSTRUMENT_CURRENCY_ERROR = 1200

    # auth service error

    def __call__(self, *args, **kwargs):
        return self.to_error(*args, **kwargs)

    def to_error(self, *args, http_code=200, **kwargs):
        error_code, (en_msg, ch_msg) = self.value
        lang = 'en'
        if has_request_context():
            lang = request.cookies.get('lang', 'en')
        if lang == 'en':
            msg = en_msg.format(*args, **kwargs)
        else:
            msg = ch_msg.format(*args, **kwargs)
        if lang == 'tc':
            msg = zhc(msg, 'zh-hk')
        return GreeksApiError(error_code, msg, http_code=http_code)


if __name__ == '__main__':
    print(ErrorCode.NO_EXIST('example'))
